﻿using AutoMapper;
using BaseData.Domain;
using BaseData.ErrorCode;
using BaseData.Infrastructure.DTO;
using BaseData.Infrastructure.Interfaces;
using CSRedis;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;

namespace BaseData.Infrastructure.Metting
{
    public class MettingService : IMettingService
    {
        private readonly IBaseRepository<MettingRoom> metRep;
        private readonly IBaseRepository<MettingRoomAddress> addRep;
        private readonly IMapper mapper;
        private readonly IBaseRepository<Users> userRep;
        private readonly IBaseRepository<MettingBooking> bookRep;
        private readonly IBaseRepository<MeetingTemplate> temRep;
        private readonly CSRedisClient csredis;
        private readonly IBaseRepository<Approvals> approvalRep;

        public MettingService(IBaseRepository<MettingRoom> metRep, IBaseRepository<MettingRoomAddress> addRep,IMapper mapper,IBaseRepository<Users> userRep,IBaseRepository<MettingBooking> bookRep,IBaseRepository<MeetingTemplate> temRep,CSRedisClient csredis,IBaseRepository<Approvals> approvalRep)
        {
            this.metRep = metRep;
            this.addRep = addRep;
            this.mapper = mapper;
            this.userRep = userRep;
            this.bookRep = bookRep;
            this.temRep = temRep;
            this.csredis = csredis;
            this.approvalRep = approvalRep;
        }
        #region  会议室管理
        /// <summary>
        /// 新增会议室
        /// </summary>
        /// <param name="metting"></param>
        /// <returns></returns>
        public async Task<int> AddMetting(MettingRoom metting)
        {
            var res = await metRep.GetAlls(x => x.MeetRoomName == metting.MeetRoomName).ToListAsync();
            if (res.Count > 0)
            {
                return -1;//会议室名称已存在
            }
            return await metRep.AddAsync(metting);
        }


        /// <summary>
        /// 新增会议室地址
        /// </summary>
        /// <param name="address"></param>
        /// <returns></returns>
        public async Task<int> AddRoomAddress(MettingRoomAddress address)
        {
            
            return await addRep.AddAsync(address);
        }
        /// <summary>
        /// 删除会议室
        /// </summary>
        /// <param name="MeetRoomId"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> DelMetting(int MeetRoomId)
        {
            var res = await metRep.DelAsync(MeetRoomId);
            return  res;
        }

        /// <summary>
        /// 显示会议地址信息
        /// </summary>
        /// <returns></returns>
        public async Task<List<MettingRoomAddress>> GetAddress()
        {
            var resisAddress = await csredis.GetAsync<List<MettingRoomAddress>>("Address");
            if (resisAddress != null)
            {
                return resisAddress;
            }
            else
            {
                var res = await addRep.GetAll().ToListAsync();
                resisAddress = res;
                var result = await csredis.SetAsync("Address",resisAddress);
            }
            return resisAddress;
        }
        /// <summary>
        /// 显示会议管理信息
        /// </summary>
        /// <param name="index"></param>
        /// <param name="size"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<PaggingResult<List<MettingDto>>> GetMetting(int index, int size, string? name)
       {
            var res = await metRep.GetAll().ToListAsync();
            if (!string.IsNullOrEmpty(name))
            {
                res = res.Where(x => x.MeetRoomName.Contains(name)).ToList();
            }
            int c = res.Count();
            int p = (int)Math.Ceiling(c * 1.0 / size);
            res = res.OrderBy(x=>x.MeetRoomId).Skip((index-1)*size).Take(size).ToList();
            var dto = mapper.Map<List<MettingDto>>(res);
            foreach (var item in dto)
            {
                item.RoomAddressName = addRep.GetAll().FirstOrDefault(x => x.RoomAddressId == item.RoomAddressId).RoomAddressName;
                item.UserName = userRep.GetAll().FirstOrDefault(x => x.UsersId == item.UserId).UserName;
            }
            return new PaggingResult<List<MettingDto>>
            {
                Data = dto,
                Count = c,
                Pages = p,
            };
        }
        /// <summary>
        /// 修改会议室信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> UpdMetting(MettingRoom dto)
        {
            var res = await metRep.UpdateAsync(dto);
            return res;
        }
        #endregion

        #region  会议预约管理
        /// <summary>
        /// 新增会议预约
        /// </summary>
        /// <param name="book"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> AddMettingBook(MettingBooking book)
        {
            try
            {
                using (var tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    await bookRep.AddAsync(book);
                    var id = book.BookId;
                    await approvalRep.AddAsync(new Approvals
                    {
                        BookId = id,
                        RoomAddressName = addRep.GetAll().FirstOrDefault(x => x.RoomAddressId == book.AddressId)?.RoomAddressName,
                        MeetRoomName = metRep.GetAll().FirstOrDefault(x => x.MeetRoomId == book.MeetRoomId)?.MeetRoomName,
                        Subject = book.Subject,
                        UserId = book.UserId,
                        BeginTime = book.StartTime,
                        EndTime = book.EndTime,
                        Attendance = 20,
                        SubmissionTime = DateTime.Now,
                        MettingContent = book.MettingContent,
                        Status = Approvals.ApprovalState.待审批,
                        Result = Approvals.ApprovalResult.待审批
                    }
                    );
                    tran.Complete();
                }
                return 1;
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 显示会议模版
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<List<MeetingTemplate>> GetMeetingTemplates()
        {
            var res = await temRep.GetAll().ToListAsync();
            return res;
        }
        /// <summary>
        /// 显示会议室预约
        /// </summary>
        /// <param name="index">页码</param>
        /// <param name="size">页容量</param>
        /// <param name="name">会议室名称</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<PaggingResult<List<MettingBookDto>>> GetMettingBook(int index, int size, int templateId)
        {
            var res = await bookRep.GetAll().ToListAsync();
            if(templateId>0)
            {
                res = res.Where(x=>x.TemplateId==templateId).ToList();
            }
            int c = res.Count();
            int p = (int)Math.Ceiling(c * 1.0 / size);
            res = res.OrderBy(x => x.BookId).Skip((index - 1) * size).Take(size).ToList();
            var dto = mapper.Map<List<MettingBookDto>>(res);
            foreach(var item in dto)
            {
                item.MeetRoomName = metRep.GetAll().FirstOrDefault(x=>x.MeetRoomId==item.MeetRoomId)?.MeetRoomName;
                item.TemplateName= temRep.GetAll().FirstOrDefault(x=>x.TemplateId==item.TemplateId)?.TemplateName;
                item.UserName = userRep.GetAll().FirstOrDefault(x => x.UsersId == item.UserId)?.UserName;
                item.RoomAddressName = addRep.GetAll().FirstOrDefault(x => x.RoomAddressId == item.AddressId)?.RoomAddressName;
            }
            return new PaggingResult<List<MettingBookDto>>
            {
                Count = c,
                Pages = p,
                Data = dto
            };
        }

        /// <summary>
        /// 删除会议预约
        /// </summary>
        /// <param name="BookId"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> DelMettingBook(int BookId)
        {
            var res = await bookRep.DelAsync(BookId);
            return res;
        }
        /// <summary>
        /// 修改会议预约
        /// </summary>
        /// <param name="book"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> UpdMettingBook(MettingBooking book)
        {
            var res = await bookRep.UpdateAsync(book);
            return res;

        }



        #endregion
    }
}
